/**通用工具函数
 * 
 */
const log4js = require('./log4j')
const CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001, // 参数错误
  USER_ACCOUNT_ERROR: 20001, // 账号和密码错误
  USER_LOGIN_ERROR: 30001, // 用户未登录
  BUSINESS_ERROR: 40001, // 业务请求失败
  AUTH_ERROR: 50001 // 认证失败或token过期
}
// 抛出全局错误
const emitError = (ctx, errorMsg) => {
  const error = new Error(errorMsg)
  return ctx.app.emit('error', error, ctx)
}
// 分页
const pager = ({pageNum = 1, pageSize = 10}) => {
  pageNum *= 1
  pageSize *= 1
  const skipIndex = (pageNum - 1) * pageSize
  return {
    page: {
      pageNum,
      pageSize
    },
    skipIndex
  }
}
// 接口成功
const success = (msg = '', data = '', code = CODE.SUCCESS) => {
  log4js.debug('data')
  return {
    code,
    data,
    msg,
    success: true
  }
}
// 接口失败
const fail = (msg = '', data = '', code = CODE.BUSINESS_ERROR) => {
  log4js.debug('msg')
  return {
    code,
    data,
    msg,
    success: false
  }
}
// 全局异常处理
const errorHandler = (error, ctx, code = CODE.BUSINESS_ERROR) => {
  log4js.debug(error.message)
  ctx.body = {
    code,
    msg: error.message,
    success: false
  }
}
module.exports = {
  /**
   * @param {number} pageNum
   * @param {number} pageSize
   */
  CODE,
  pager,
  success,
  fail,
  emitError,
  errorHandler,
}